package com.bqnxzz.ywiigame.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.AttributeSet;

import android.util.Log;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebSettings;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bqnxzz.ywiigame.MainActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import ren.yale.android.cachewebviewlib.CacheWebView;
import ren.yale.android.cachewebviewlib.WebViewCache;

public class X5WebView extends CacheWebView {
    public final static String TAG = "H5_X5WebView";

    public String initJsData;

    public final static int CHOOSER_REQUEST = 0x33;
    public final static int PERMISSION_REQUEST = 0x44;

    private ValueCallback<Uri[]> uploadFiles;

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            Log.d(TAG, "shouldOverrideUrlLoading:" + url);
            return true;
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @Override
        public void onPageStarted(WebView view, String url, android.graphics.Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView webview, String var2) {
//            if (BuildConfig.DEBUG) {
//                if (MainActivity.self.hallView == webview) {
//                    loadUrl("javascript:loadSingleScript('corelib/vconsole.min.js', function(){})");
//                } else {
//                    loadUrl("javascript:loadSingleScript('../hall/corelib/vconsole.min.js', function(){})");
//                }
//            }
            super.onPageFinished(webview, var2);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, final WebResourceRequest request) {
//            if (BuildConfig.DEBUG) {
//                Log.d(TAG, request.getUrl().toString());
//            }
            return super.shouldInterceptRequest(view, request);
        }
    };

    private WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            if (ContextCompat.checkSelfPermission(MainActivity.self, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                X5WebView x5WebView = (X5WebView) webView;
                x5WebView.checkImagePermissions();
                return false;
            }
            uploadFiles = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false); // 是否允许多选
            i.setType("image/*"); // 设置文件类型
            String[] mimeTypes = { "image/*" }; // 文件类型列表
            i.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes); // 设置多种类型
            i.addCategory(Intent.CATEGORY_OPENABLE);
            MainActivity.self.startActivityForResult(Intent.createChooser(i, "Image Chooser"), CHOOSER_REQUEST);
            return true;
        }
    };

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context arg0) {
        super(arg0);
        this.setWebViewClient(webViewClient);
        this.setWebChromeClient(webChromeClient);
        initWebViewSettings();
    }

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        this.setWebViewClient(webViewClient);
        this.setWebChromeClient(webChromeClient);
        initWebViewSettings();
    }

    public void callJS(String funName, String data) {
        String jsCode = "javascript:if(__XYExternalInterface__CALL){__XYExternalInterface__CALL('" + funName + "','" + data + "');}";
//        loadUrl(jsCode);
        MainActivity.self.runOnUiThread(() -> loadUrl(jsCode));
    }

    public void callJS(String funName) {
        String jsCode = "javascript:if(__XYExternalInterface__CALL){__XYExternalInterface__CALL('" + funName + "');}";
//        loadUrl(jsCode);
        MainActivity.self.runOnUiThread(() -> loadUrl(jsCode));
    }

    private void initWebViewSettings() {
        CacheWebView.getCacheConfig().setDiskMaxSize(1024*1024*300);
        CacheWebView.getCacheConfig().setRamMaxSize(1024*1024*200);
        CacheWebView.getCacheConfig().enableDebug(false);
        CacheWebView.getCacheConfig().setEncodeBufferSize(1024);
        this.getWebViewCache().getStaticRes()
                .addExtension("ac3")
                .addRamExtension("png")
                .addRamExtension("jpg")
                .addRamExtension("jpeg")
                .addRamExtension("ac3");
        WebSettings webSetting = this.getSettings();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webSetting.setUserAgentString("app/qp;android;Android");//添加UA,  “app/XXX”：是与h5商量好的标识，h5确认UA为app/XXX就认为该请求的终端为App
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSetting.setAllowUniversalAccessFromFileURLs(true);
        }
        webSetting.setAllowContentAccess(true);
        webSetting.setAllowFileAccess(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            webSetting.setAllowFileAccessFromFileURLs(true);
        }
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
//        webSetting.setAppCacheEnabled(true);
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
//        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSetting.setMediaPlaybackRequiresUserGesture(false);
        }
//        WebView.setWebContentsDebuggingEnabled(true);
        String appCachePath = MainActivity.self.getApplication().getCacheDir().getAbsolutePath();
//        webSetting.setAppCachePath(appCachePath);
    }

    public void onActivityResultFileChooser(int requestCode, int resultCode, Intent intent) {
        if (requestCode != CHOOSER_REQUEST || uploadFiles == null) {
            return;
        }
        if (resultCode == Activity.RESULT_OK) {
            Uri[] results = null;
            if (intent != null) {
                String dataString = intent.getDataString();
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }
            }
            uploadFiles.onReceiveValue(results);
        } else {
            uploadFiles.onReceiveValue(null);
        }
        uploadFiles = null;
    }

    public void checkImagePermissions() {
        List<String> permissiongList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(MainActivity.self, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissiongList.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!permissiongList.isEmpty()) {
            String[] permissions = permissiongList.toArray(new String[permissiongList.size()]);
            ActivityCompat.requestPermissions(MainActivity.self, permissions, PERMISSION_REQUEST);
        }
    }

    public void clearCache() {
        this.clearFormData();
        this.clearHistory();
        this.clearCache(true);
        deleteDir(MainActivity.self.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            deleteDir(MainActivity.self.getExternalCacheDir());
            MainActivity.self.deleteDatabase("webview.db");
            MainActivity.self.deleteDatabase("webviewCache.db");
        }
    }

    private static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
            return dir.delete();
        }
        if (dir != null) {
            return dir.delete();
        } else {
            return false;
        }
    }
}

